<template>
  <div>


    <el-table
      border
      :data="categoryList"
      lazy
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      style="width: 900px;margin-bottom: 20px;"
      :load="load"

      :row-key="getRowKey"
      :row-class-name="tableRowClassName"
    >
      <el-table-column align="center" prop="id" label="分类id" width="180"></el-table-column>
      <el-table-column prop="name" label="分类名称"> </el-table-column>
      <el-table-column prop="address" label="操作" width="250">
        <template slot="header" slot-scope="scope">
          <el-input
            size="mini"
            v-model="saveKey"
            @change="addCategory"
            placeholder="按Enter键添加一级分类"/>
        </template>

        <template slot-scope="scope">
          <HintButton v-if="$hasBP('btn.Category.add')" title="添加子分类" @click="openAadd(scope)" :disabled="!scope.row.level"
                      size="mini" type="primary" icon="el-icon-plus"/>
          <HintButton v-if="$hasBP('btn.Category.update')" @click="openEdit(scope)" title="修改分类"
                      size="mini" type="primary" icon="el-icon-edit"/>

          <HintButton v-if="$hasBP('btn.Category.remove')" @click="delOne(scope)" title="删除分类"
                      size="mini" type="danger" icon="el-icon-delete"/>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="分类名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="toAddSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import getList from '@/api/category';
export default {
  name: "Category",
  data(){
    return {
      categoryList : [],
      saveKey:'',
      dialogFormVisible:false,
      formLabelWidth: '120px',
      title:'新增子分类',
      form:{
        name:'',
      },
      handleType : 'add',
      currentCategoryId : 0,
      currentCategoryLevel : 1,
      parentId : 0,
    }
  },
  mounted() {
    // console.log(getList)
    this.getCategory1List();
  },
  methods:{
    async addCategory(value){
      let res = await this.$ajax.category.addCategory1(value);
      if (res.code == 200) {
        this.saveKey = '';
      }
      this.getCategory1List();
    },
    getCategory1List() {
      this.$ajax.category.getCategorys1().then(v => {
        console.log(v);
        if (v.code == 200) {
          let result = v.data;
          result.forEach(item => {
            item.hasChildren = true;
            item.level = 1;
          })

          this.categoryList = result;
        }
      })
    },
    async load(row, treeNode, resolve) {
      console.log('---', row, treeNode);
      if (row.level===1) {
        const categorys2 = await this.getCategorys2(row)
        resolve(categorys2)
      } else if (row.level===2) {
        const categorys3 = await this.getCategorys3(row)
        resolve(categorys3)
      }

    },
    getCategorys2 (row) {
      return this.$ajax.category.getCategorys2(row.id).then(result => {
        const categorys2 = result.data
        if (categorys2 && categorys2.length>0) {
          categorys2.forEach(item => {
            // 标识有子分类
            item.hasChildren = true
            // 分类级别为2级
            item.level = 2
          })
          return categorys2
        } else {
          row.hasChildren = false
          return []
        }
      })
    },

    async getCategorys3 (row) {
      const result = await this.$ajax.category.getCategorys3(row.id)
      const categorys3 = result.data
      if (categorys3 && categorys3.length>0) {
        return categorys3
      } else {
        row.hasChildren = false
        return []
      }
    },
    getRowKey (row) {
      return row.level + '-' + row.id
    },

    /*
    返回二级分类列表的类名
    */
    tableRowClassName({row, rowIndex}) {
      if (row.level === 2) {
        return 'level2-row'
      }
    },
    delOne(scope) {
      this.$confirm(`确定删除吗?`, '提示', {
        type: 'warning'
      }).then(async ()=>{
        let res = await this.$ajax.category.delCategory(scope.row);
        console.log(res);
        this.$message({
          type: 'success',
          message: '删除成功!'
        })

        this.getCategory1List()
      }).catch(error=>{
        if (error==='cancel') {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        }
      });

    },

    openAadd(scope) {
      this.dialogFormVisible = true;
      let title = scope.row.level == 1 ? '二' : '三';
      this.title = `新增${title}级子分类`;
      this.currentCategoryId = scope.row.id;
      this.currentCategoryLevel = scope.row.level;
    },
    async toAddSave(){
      this.dialogFormVisible = false;

      if (this.handleType == 'add') {
        if (this.currentCategoryLevel == 1) {
          let res = await this.$ajax.category.addCategory2(this.form.name, this.currentCategoryId);
          // this.getCategorys2({id:this.currentCategoryId});
        } else {
          let res = await this.$ajax.category.addCategory3(this.form.name, this.currentCategoryId);
          // this.getCategorys3({id:this.currentCategoryId});
        }
        this.form.name = '';
        this.getCategory1List();
      }
      if (this.handleType == 'edit') {
        if (this.currentCategoryLevel == 1) {
          let res = await this.$ajax.category.editCategory1(this.currentCategoryId,this.form.name);
        } else if (this.currentCategoryLevel == 2) {
          let res = await this.$ajax.category.editCategory2(this.parentId, this.currentCategoryId,this.form.name);
          // this.getCategorys2({id:this.parentId});
          //
          // this.load({id:this.parentId, level:1})
        } else {
          let res = await this.$ajax.category.editCategory3(this.parentId, this.currentCategoryId,this.form.name);
          // this.getCategorys3({id:this.parentId});
        }
        this.form.name = '';
        // this.$router.go(0);
        this.getCategory1List();
      }
    },
    openEdit(scope) {
      console.log(scope);
      this.dialogFormVisible = true;
      this.title = `修改分类名称`;
      this.currentCategoryId = scope.row.id;
      this.currentCategoryLevel = scope.row.level;
      this.handleType = 'edit';
      if (scope.row.category1Id){
        this.parentId = scope.row.category1Id;
      } else if (scope.row.category2Id) {
        this.parentId = scope.row.category2Id;
      } else {
        this.parentId = 0;
      }

      console.log(this.handleType);
    },

  }
}
</script>
